package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"net"
	"time"
)

var addr string

func init() {
	rand.Seed(time.Now().UnixNano())
}

func main() {
	addr = fmt.Sprintf("%s:%d", AddressByName("br0"), rand.Intn(65530))
	var role = flag.String("role", "", "master | worker")
	flag.Parse()
	hosts := []string{"http://127.0.0.1:2379"}
	switch *role {
	case "master":
		master, _ := NewMaster(hosts, "/workers")
		master.WatchWorkers()
	case "worker":
		worker, _ := NewWorker(hosts, addr, "/workers")
		worker.HeartBeat()
	}
}

func AddressByName(face string) string {
	ifs, err := net.InterfaceByName(face)
	if err != nil {
		log.Fatal(err)
	}

	addrs, err := ifs.Addrs()
	if err != nil {
		log.Fatal(err)
	}

	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}

	return ""
}
